package lumis.service.wsrp.producer;

import javax.persistence.NoResultException;

import lumis.doui.control.button.AddButtonControl;
import lumis.portal.PortalException;
import lumis.portal.manager.ManagerFactory;
import lumis.util.XmlUtil;

/**
 * {@link AddButtonControl} responsible for opening the add interface. If the
 * current service instance isn't configured yet the button doesn't create a
 * popup link for the add interface. Instead, it creates an alert in JavaScript
 * to alert user that this service instance isn't configured yet.
 * 
 * @version $Revision: 11180 $ $Date: 2009-12-04 18:13:02 -0200 (Fri, 04 Dec 2009) $
 * @since 5.5.0
 */
public class ProducerAdministrationListAddButtonControl extends AddButtonControl
{
	@Override
	public void setRenderData() throws PortalException
	{
		// get the producer associated with the current service instance
		String serviceInstanceId = douiContext.getRequest().getServiceInstanceConfig().getId();
		ProducerImpl producer;
		try
		{
			producer = (ProducerImpl) ManagerFactory.getEntityManager().createNamedQuery(ProducerImpl.NAMED_QUERY_FIND_PRODUCER_BY_NAMESPACE).setParameter("namespace", serviceInstanceId)
					.getSingleResult();
		}
		catch (NoResultException e)
		{
			producer = null;
		}

		// if producer exists then service instance is configured. so we might
		// proceed with
		// the normal renderization. otherwise, we must not permit the
		// renderization of the link
		if (producer != null)
			super.setRenderData();
		else
		{
			StringBuilder onClickXml = new StringBuilder();
			onClickXml.append(XmlUtil.XML_HEADER + "<onClick type=\"script\">");
			onClickXml.append("<script><![CDATA[");
			onClickXml.append(XmlUtil.encodeXml("alert('" + localize("STR_CONFIGURATION_NOT_FOUND") + "');"));
			onClickXml.append("]]></script>");
			onClickXml.append("</onClick>");
			XmlUtil.addNodeFromXmlString(controlDefinitionNode, onClickXml.toString());

			super.setRenderData();
		}
	}
}
